// src/Home.tsx
import { useState, useEffect } from 'react';
import { Layout, Row, Col, Card, Input, Button, message, Carousel, Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import Sidebar from './Sidebar';
import RecommendationService from './services/recommendationService';

const { Header, Content } = Layout;

const TAGS = ['早餐', '午餐', '晚餐', '下午茶'];
const CATEGORIES = ['川菜', '粤菜', '鲁菜', '淮扬菜', '闽菜', '徽菜', '湘菜', '浙菜'];

interface Recipe {
  id: string;
  title: string;
  coverImage: string;
  description?: string;
}

function Home() {
  const navigate = useNavigate();
  const [recommendedRecipes, setRecommendedRecipes] = useState<Recipe[]>([]);
  const [recommendedLoading, setRecommendedLoading] = useState<boolean>(true);
  const [bannerRecipes, setBannerRecipes] = useState<Recipe[]>([]);
  const [bannerLoading, setBannerLoading] = useState<boolean>(true);

  // 获取轮播图菜谱数据
  const fetchBannerRecipes = async () => {
    try {
      setBannerLoading(true);
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      if (!token) {
        console.log('未找到token，使用默认轮播图');
        setBannerRecipes([
          {
            id: '1',
            title: '精选美食',
            coverImage: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
            description: '发现美味佳肴'
          },
          {
            id: '2',
            title: '精致料理',
            coverImage: 'https://images.unsplash.com/photo-1565958011703-44f9829ba187?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
            description: '品味生活美学'
          },
          {
            id: '3',
            title: '家常美味',
            coverImage: 'https://images.unsplash.com/photo-1567620905732-2d1ec7ab7445?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
            description: '家的味道最温馨'
          },
          {
            id: '4',
            title: '甜品时光',
            coverImage: 'https://images.unsplash.com/photo-1563379926898-05f4575a45d8?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
            description: '甜蜜时刻'
          }
        ]);
        return;
      }

      // 获取热门菜谱作为轮播图数据（按收藏数排序）
      const response = await fetch('/api/recipe/search?keyword=&sortBy=favoriteCount&sortOrder=desc&limit=8', {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (response.ok) {
        const recipesData = await response.json();
        console.log('轮播图菜谱数据:', recipesData);
        
        if (Array.isArray(recipesData) && recipesData.length > 0) {
          // 格式化数据并取前4个作为轮播图
          const formattedRecipes = recipesData.slice(0, 4).map((recipe: any) => ({
            id: recipe.id || recipe.recipeId || `recipe_${Date.now()}`,
            title: recipe.title || recipe.recipeName || '精选菜谱',
            coverImage: recipe.coverImage || recipe.image || recipe.photo,
            description: recipe.description || '美味佳肴'
          }));
          
          setBannerRecipes(formattedRecipes);
        } else {
          // 如果没有数据，使用默认图片
          setBannerRecipes([
            {
              id: '1',
              title: '精选美食',
              coverImage: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
              description: '发现美味佳肴'
            },
            {
              id: '2',
              title: '精致料理',
              coverImage: 'https://images.unsplash.com/photo-1565958011703-44f9829ba187?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
              description: '品味生活美学'
            },
            {
              id: '3',
              title: '家常美味',
              coverImage: 'https://images.unsplash.com/photo-1567620905732-2d1ec7ab7445?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
              description: '家的味道最温馨'
            },
            {
              id: '4',
              title: '甜品时光',
              coverImage: 'https://images.unsplash.com/photo-1563379926898-05f4575a45d8?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
              description: '甜蜜时刻'
            }
          ]);
        }
      } else {
        throw new Error('获取轮播图数据失败');
      }
    } catch (error) {
      console.error('获取轮播图菜谱失败:', error);
      // 使用默认轮播图
      setBannerRecipes([
        {
          id: '1',
          title: '精选美食',
          coverImage: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
          description: '发现美味佳肴'
        },
        {
          id: '2',
          title: '精致料理',
          coverImage: 'https://images.unsplash.com/photo-1565958011703-44f9829ba187?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
          description: '品味生活美学'
        },
        {
          id: '3',
          title: '家常美味',
          coverImage: 'https://images.unsplash.com/photo-1567620905732-2d1ec7ab7445?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
          description: '家的味道最温馨'
        },
        {
          id: '4',
          title: '甜品时光',
          coverImage: 'https://images.unsplash.com/photo-1563379926898-05f4575a45d8?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80',
          description: '甜蜜时刻'
        }
      ]);
    } finally {
      setBannerLoading(false);
    }
  };

  // 智能图片URL处理函数
  const getImageUrl = (coverImage: string) => {
    if (!coverImage) {
      return 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&auto=format&fit=crop&w=2080&q=80';
    }
    
    // 如果已经是完整URL，直接返回
    if (coverImage.startsWith('http')) {
      return coverImage;
    }
    
    // 如果是相对路径，拼接基础URL
    return `http://218.244.141.86:8080${coverImage}`;
  };

  const handleSearch = (keyword: string) => {
    const query = keyword.trim();
    if (!query) {
      message.warning('请输入搜索内容');
      return;
    }

    if (TAGS.includes(query)) {
      navigate(`/tag/${query}`);
    } else if (CATEGORIES.includes(query)) {
      navigate(`/category/${query}`);
    } else {
      message.warning('暂未收录该分类或标签');
    }
  };

  // 获取推荐菜谱
  useEffect(() => {
    const fetchRecommendedRecipes = async () => {
      try {
        setRecommendedLoading(true);
        const userId = localStorage.getItem('userId');
        if (!userId) {
          throw new Error('未找到用户ID');
        }
        const rawRecommended = await RecommendationService.getTop5Recommendations(userId);
        console.log('推荐接口返回的原始数据:', rawRecommended);

        // 格式化推荐数据
        const formattedRecommended = rawRecommended.map((recipe: any, index: number) => ({
          id: recipe.id || recipe.recipeId || recipe._id || `recipe_${index}_${Date.now()}`,
          title: recipe.title || recipe.name || recipe.recipeName || '未知菜谱',
          coverImage: getImageUrl(recipe.coverImage || recipe.image || recipe.photo),
        }));

        setRecommendedRecipes(formattedRecommended);
      } catch (error) {
        console.error('获取推荐菜谱失败:', error);
        // 设置默认推荐菜谱
        setRecommendedRecipes([
          { 
            id: '1', 
            title: '宫保鸡丁', 
            coverImage: getImageUrl('') 
          },
          { 
            id: '2', 
            title: '麻婆豆腐', 
            coverImage: getImageUrl('') 
          },
          { 
            id: '3', 
            title: '红烧肉', 
            coverImage: getImageUrl('') 
          },
          { 
            id: '4', 
            title: '糖醋里脊', 
            coverImage: getImageUrl('') 
          },
        ]);
      } finally {
        setRecommendedLoading(false);
      }
    };

    fetchRecommendedRecipes();
    fetchBannerRecipes();
  }, []);

  return (
    <Layout
      style={{
        minHeight: '100vh',
        backgroundImage: "url('/background2.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundAttachment: 'fixed',
        backgroundRepeat: 'no-repeat',
        display: 'flex',
        overflow: 'hidden',
      }}
    >
      <Sidebar />
      <Layout style={{ 
        background: 'transparent',
        flex: 1,
        overflow: 'hidden'
      }}>
        <div style={{ 
          height: '100vh',
          overflowY: 'auto',
          paddingRight: '8px',
          scrollbarWidth: 'thin',
          scrollbarColor: '#e8d9c7 transparent'
        }}>
          <Header
            style={{
              background: 'transparent',
              padding: '40px 60px 20px 60px',
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: '10px',
              height: 'auto',
              minHeight: '80px',
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                gap: '10px',
                width: '100%',
                marginBottom: '10px',
              }}
            >
              <Input
                placeholder="请输入搜索内容（如：早餐、川菜）"
                prefix={<SearchOutlined />}
                style={{
                  width: '600px',
                  height: '40px',
                  borderRadius: '30px',
                  borderColor: '#e8d9c7',
                  backgroundColor: 'rgba(255, 255, 255, 0.85)',
                  backdropFilter: 'blur(5px)',
                }}
                onPressEnter={(e) => {
                  handleSearch(e.currentTarget.value);
                }}
              />
              <Button
                type="primary"
                style={{
                  backgroundColor: 'rgba(232, 217, 199, 0.9)',
                  borderColor: '#e8d9c7',
                  borderRadius: '20px',
                  color: '#333',
                  fontWeight: '500',
                }}
                onClick={() => {
                  const input = document.querySelector('input[placeholder*="搜索"]') as HTMLInputElement;
                  if (input) handleSearch(input.value);
                }}
              >
                搜索
              </Button>
            </div>

            {/* 轮播图部分 */}
            <div style={{ width: '100%', maxWidth: '1200px', marginTop: '20px' }}>
              {bannerLoading ? (
                <div style={{ 
                  height: '300px', 
                  display: 'flex', 
                  alignItems: 'center', 
                  justifyContent: 'center',
                  backgroundColor: 'rgba(255,255,255,0.1)',
                  borderRadius: '16px'
                }}>
                  <Spin size="large" />
                  <span style={{ marginLeft: 10, color: '#8b4513' }}>加载轮播图中...</span>
                </div>
              ) : (
                <Carousel 
                  autoplay 
                  autoplaySpeed={5000} 
                  dots={{ className: 'custom-dots' }}
                  style={{
                    borderRadius: '16px',
                    overflow: 'hidden',
                    boxShadow: '0 8px 32px rgba(0,0,0,0.15)',
                  }}
                >
                  {bannerRecipes.map((recipe) => (
                    <div key={recipe.id}>
                      <div
                        style={{
                          height: '300px',
                          backgroundImage: `url(${getImageUrl(recipe.coverImage)})`,
                          backgroundSize: 'cover',
                          backgroundPosition: 'center',
                          backgroundRepeat: 'no-repeat',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          cursor: 'default',
                        }}
                      >
                        <div
                          style={{
                            backgroundColor: 'rgba(0, 0, 0, 0.4)',
                            padding: '20px 40px',
                            borderRadius: '12px',
                            backdropFilter: 'blur(10px)',
                            textAlign: 'center',
                          }}
                        >
                          <h3
                            style={{
                              color: 'white',
                              fontSize: '28px',
                              fontWeight: 'bold',
                              margin: '0 0 8px 0',
                              textShadow: '2px 2px 4px rgba(0,0,0,0.5)',
                            }}
                          >
                            {recipe.title}
                          </h3>
                          {recipe.description && (
                            <p
                              style={{
                                color: 'rgba(255,255,255,0.9)',
                                fontSize: '16px',
                                margin: 0,
                                textShadow: '1px 1px 2px rgba(0,0,0,0.5)',
                              }}
                            >
                              {recipe.description}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>
                  ))}
                </Carousel>
              )}
            </div>
          </Header>

          <Content
            style={{
              margin: '0 40px',
              padding: '30px 20px',
              background: 'transparent',
            }}
          >
            {/* 分类（tag） */}
            <div style={{ marginBottom: '40px' }}>
              <h2
                style={{
                  fontSize: '24px',
                  fontWeight: 'bold',
                  marginBottom: '20px',
                  textAlign: 'center',
                  color: '#333',
                  textShadow: '0 1px 2px rgba(255,255,255,0.8)',
                }}
              >
                分类
              </h2>
              <Row gutter={[20, 20]} justify="center">
                {TAGS.map((name) => {
                  const iconMap: Record<string, string> = {
                    早餐: '🍞',
                    午餐: '🍜',
                    晚餐: '🍲',
                    下午茶: '🍰',
                  };
                  const colorMap: Record<string, string> = {
                    早餐: 'rgba(249, 224, 179, 0.9)',
                    午餐: 'rgba(255, 229, 204, 0.9)',
                    晚餐: 'rgba(253, 230, 211, 0.9)',
                    下午茶: 'rgba(255, 240, 230, 0.9)',
                  };
                  return (
                    <Col key={name} xs={12} sm={8} md={6} lg={6}>
                      <Card
                        hoverable
                        style={{
                          textAlign: 'center',
                          backgroundColor: 'rgba(255, 255, 255, 0.85)',
                          borderRadius: '12px',
                          border: `1px solid ${colorMap[name]}`,
                          padding: '20px',
                          backdropFilter: 'blur(8px)',
                          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                          transition: 'all 0.3s ease',
                          cursor: 'pointer',
                        }}
                        bodyStyle={{ padding: '16px' }}
                        onClick={() => navigate(`/tag/${name}`)}
                      >
                        <div style={{ fontSize: '36px', marginBottom: '12px' }}>{iconMap[name]}</div>
                        <div style={{ fontSize: '16px', fontWeight: '500' }}>{name}</div>
                      </Card>
                    </Col>
                  );
                })}
              </Row>
            </div>

            {/* 今日推荐 */}
            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
                <h2
                  style={{
                    fontSize: '24px',
                    fontWeight: 'bold',
                    margin: 0,
                    color: '#333',
                    textShadow: '0 1px 2px rgba(255,255,255,0.8)',
                  }}
                >
                  今日推荐
                </h2>
                {/* 删除测试推荐接口按钮 */}
              </div>
              {recommendedLoading ? (
                <div style={{ textAlign: 'center', padding: '20px', color: '#666' }}>加载中...</div>
              ) : (
                <Row gutter={[24, 24]} justify="center">
                  {recommendedRecipes.slice(0, 4).map((recipe) => (
                    <Col key={recipe.id} xs={12} sm={8} md={6} lg={6}>
                      <div
                        style={{
                          textAlign: 'center',
                          padding: '16px',
                          borderRadius: '12px',
                          border: '1px solid rgba(238, 238, 238, 0.5)',
                          backgroundColor: 'rgba(255, 255, 255, 0.85)',
                          transition: 'all 0.3s ease',
                          backdropFilter: 'blur(8px)',
                          boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                          cursor: 'pointer',
                        }}
                        onClick={() => navigate(`/recipe/${recipe.id}`, { state: { recipe } })}
                      >
                        <img
                          src={getImageUrl(recipe.coverImage)}
                          alt={recipe.title}
                          style={{
                            width: '100%',
                            height: '160px',
                            objectFit: 'cover',
                            borderRadius: '8px',
                          }}
                          onError={(e) => {
                            e.currentTarget.src = 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&auto=format&fit=crop&w=300&q=80';
                          }}
                        />
                        <div
                          style={{
                            marginTop: '12px',
                            fontSize: '16px',
                            fontWeight: 'bold',
                            color: '#333',
                          }}
                        >
                          {recipe.title}
                        </div>
                      </div>
                    </Col>
                  ))}
                </Row>
              )}
            </div>
          </Content>
        </div>
      </Layout>
    </Layout>
  );
}

export default Home;